from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTextEdit
from PyQt5.QtCore import pyqtSignal, QObject


class LogSignals(QObject):
    new_log = pyqtSignal(str)


class LogViewer(QWidget):
    def __init__(self, parent=None):
        super(LogViewer, self).__init__(parent)

        # 创建信号对象
        self.signals = LogSignals()
        self.signals.new_log.connect(self._append_log_safe)

        self.layout = QVBoxLayout()
        self.log_display = QTextEdit()
        self.log_display.setReadOnly(True)

        self.layout.addWidget(self.log_display)
        self.setLayout(self.layout)

    def append_log(self, message):
        """线程安全的日志添加方法"""
        self.signals.new_log.emit(message)

    def _append_log_safe(self, message):
        """在主线程中实际添加日志"""
        self.log_display.append(message)
        # 自动滚动到底部
        self.log_display.verticalScrollBar().setValue(
            self.log_display.verticalScrollBar().maximum()
        )
